package com.leetcode.search.backtracking;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Dennis Li
 * @date 2020/7/29 13:34
 */
public class GenerateParenthesis_22 {

    private int n;
    private List<String> res = new ArrayList<>();

    public List<String> generateParenthesis(int n) {
        this.n = n;
        backtrack(0, 0, "");
        return res;
    }

    // 通过左右括号的选择进行剪枝
    private void backtrack(int left, int right, String s) {
        if (left == n && n == right) {
            res.add(s);
            return;
        }
        // 右边的括号数不能大于左边
        if (right > left) return;
        if (left < n) {
            // 每次s相加相当于生成了一个新的String对象
            backtrack(left + 1, right, s + "(");
        }
        if (right < n) {
            backtrack(left, right + 1, s + ")");
        }

    }


}
